import os.path

from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from userinfo.AuthorIntercept import is_login
from django.conf import settings


# Create your views here.
def login(request):
    if request.method == 'GET':
        username = request.COOKIES.get('username', '')
        password = request.COOKIES.get('password', '')
        return render(request, 'userinfo/login.html', locals())
    elif request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        remember_me = request.POST.get('remember_me', '')

        file = request.FILES['myfile']
        if file:
            print('上传文件名是:', file.name)
            if not os.path.exists(settings.MEDIA_ROOT):
                os.mkdir(settings.MEDIA_ROOT)
            filename = os.path.join(settings.MEDIA_ROOT, file.name)
            with open(filename, 'wb') as f:
                f.write(file.file.read())
        res = redirect('/userinfo/index')
        if remember_me:
            res.set_cookie('username', username, 3600)
            res.set_cookie('password', password, 3600)
        else:
            res.delete_cookie('username')
            res.delete_cookie('password')
        request.session['is_login'] = 'True'
        return res


@is_login
def index(request):
    username = request.COOKIES.get('username', '')
    password = request.COOKIES.get('password', '')
    return HttpResponse('当前用户名:' + username + "<br/>密码:" + password)


def add_session(request):
    request.session['my_session_var'] = 100
    response = HttpResponse('添加session')
    return response


def mod_session(request, new_value):
    request.session['my_session_var'] = new_value
    response = HttpResponse('修改session成功')
    return response


def del_session(request):
    try:
        del request.session['my_session_var']
        response = HttpResponse('删除session成功')
    except Exception as ex:
        print(ex)
        response = HttpResponse('删除session失败')
    return response


def show_session(request):
    my_session_var = request.session.get('my_session_var', '没有值!')
    print('my_session_var=', my_session_var)
    return HttpResponse('my_session_var=' + str(my_session_var))
